<template>
  <div class="editor">
    <a-modal
      title="发布成功"
      v-model:open="showPublishForm"
      width="700px"
      :footer="null">
      <publish-form />
    </a-modal>
    <preview-form :visible="showPreviewForm" @onClose="showPreviewForm = false"></preview-form>

    <a-layout :style="{ background: '#fff' ,display:'flex',  }">
      <a-layout-header class="header">
        <div class="page-title">
          <router-link to="/">
            <img alt="慕课乐高" src="@/assets/logo.png"  class="logo-title"/>
          </router-link>
          <inline-edit :value="page.title" @change="titleChange" :style="{height:'30px', }"></inline-edit>
        </div>
        <a-menu 
        :selectable="false"
        theme="light"
        mode="horizontal"
        >
          <a-menu-item key="1">
            <a-button type="primary" @click="preview">预览和设置</a-button>
          </a-menu-item>
          <a-menu-item key="2">
              <a-button type="primary" @click="saveWork" :loading="saveIsLoading">保存</a-button>
          </a-menu-item>
          <a-menu-item key="3">
              <a-button type="primary" @click="publish" :loading="isPublishing">发布</a-button>
          </a-menu-item>
          <a-menu-item key="4">
              <userprofile/>
          </a-menu-item>
        </a-menu>
      </a-layout-header>
    </a-layout>

    <a-layout style="min-width: 1200px;">
      <!-- 左侧组件列表 -->
      <a-layout-sider
        width="380px"
        style="
          background: white;
          height: calc(100vh - 70px);
          overflow-y: auto;
          overflow-x: hidden;
        "
      >
        <components-list
          :list="componentsText"
          :slist="componentsShape"
          @onItemClick="addItem"
        ></components-list>

        <img id="test-image" :style="{width: '300px'}"/>
      </a-layout-sider>


      <!-- 画布区域 -->
      <a-layout-content class="preview-container" style="padding: 0 24px 0 24px;height: calc(100vh - 70px)">
        <p>画布区域</p>
        
        <history-area></history-area>

        <div class="preview-list" id="canvas-ares" :class="{ 'canvas-fix': canvasFix }">
          <div
            class="body-container"
            :style="page.props"
            @click="setActive('')"
            @drop="onDrop"
            @dragover="onDragOver"
            ref="bodyContainer"
          >
            <div
              class="preview-list-component"
              v-for="item in components"
              :key="item.id"
            >
              <!-- <transition name="fade"> -->
              <edit-wrapper
                v-if="item.isHidden !== true"
                :id="item.id"
                :active="item.id === currentElement?.id"
                @setActive="setActive"
                @delete-item="deleteItem"
                :props="item.props"
                @updatePosition="changePosition"
              >
                <component
                  :is="item.name"
                  v-bind="item.props"
                  draggable="false"
                  @dragstart="onDragStart($event, item.id, item.props)"
                >
                </component>
              </edit-wrapper>
              <!-- </transition> -->
            </div>
          </div>
        </div>
      </a-layout-content>

      <!-- 右侧属性栏 -->
      <a-layout-sider
        width="380px"
        style="
          background: white;
          height: calc(100vh - 70px);
          overflow-y: auto;
          overflow-x: hidden;
        "
        class="settings-panel"
        >
        <a-tabs type="card" v-model:activeKey="activaPanel" :animated="true">
          <a-tab-pane key="component" tab="组件属性" class="no-topradius">
            <div v-if="currentElement">
              <edit-group
                v-if="!currentElement.isLock"
                :props="currentElement.props"
                @change="handleChange"
              >
              </edit-group>
              <div v-else><a-empty><template #description><p>该元素被锁定,无法编辑</p></template></a-empty></div>
            </div>
            <div v-else><a-empty><template #description><p>未选中任何元素</p></template></a-empty></div>
            <!-- 
            <pre>
            {{ currentElement && currentElement.props }}
          </pre > -->
          </a-tab-pane>
          <a-tab-pane key="layer" tab="图层属性"
            >layer
            <layer-list
              :list="components"
              @change="handleChange"
              @select="setActive"
              :selectedId="currentElement?.id"
            ></layer-list>
          </a-tab-pane>
          <a-tab-pane key="page" tab="页面设置">
            <props-table :props="page.props" @change="pageChange"></props-table>
          </a-tab-pane>
        </a-tabs>
      </a-layout-sider>
    </a-layout>
  </div>
</template>
<script lang="ts">
import LText from "@/components/LText.vue";
import LImage from "@/components/LImage.vue";
import HistoryArea from "@/components/HistoryArea.vue";
import EditGroup from "@/components/EditGroup.vue";
import LayerList from "@/components/LayerList.vue";
import LShape from "@/components/LShape.vue";
import InlineEdit from "@/components/InlineEdit.vue";
import Userprofile from "@/components/UserProfile.vue";
import PropsTable from "@/components/PropsTable.vue"; // 添加这行
import {
  Layout as aLayout,
  LayoutHeader as aLayoutHeader,
  LayoutContent as aLayoutContent,
  LayoutSider as aLayoutSider,
  Tabs as aTabs,
  TabPane as aTabPane,
  Empty as aEmpty,
  Menu as aMenu,
  MenuItem as aMenuItem,
  Button as aButton,
  Modal as aModal,
} from "ant-design-vue";
import { computed, onMounted, ref ,nextTick} from "vue";
import { useStore } from "vuex";
import { GlobalDataProps } from "@/store";
import { useRoute,RouterLink } from "vue-router";
import { pickBy, mapValues } from "lodash";
import { defaultTextTemplates } from "@/defaultTextTemplates";
import { defaultShapeTemplates } from "@/defaultShapeTemplates";
import { ComponentData } from "@/store/editor";
import ComponentsList from "@/components/ComponentsList.vue";
import EditWrapper from "@/components/EditWrapper.vue";
import PreviewForm from "@/views/editor/PreviewForm.vue";
import PublishForm from "@/views/editor/PublishForm.vue";
import initHotKeys from "@/plugins/hotKeys";
import initContextMenu from "@/components/contextMenu";
import useSaveWork from "@/hooks/useSaveWork";
import usePublishWork from "@/hooks/usePublishWork";
export default {
  components: {
    LText,
    LImage,
    LShape,
  },
};
</script>
<script lang="ts" setup>
initHotKeys();
initContextMenu();
const {saveIsLoading, saveWork } = useSaveWork();
const { publishWork, isPublishing } = usePublishWork();
const route = useRoute();
const currentWorkId = route.params.id;
const canvasFix = ref(false);
const showPublishForm = ref(false);
const showPreviewForm = ref(false);

// 由于使用的名称传递的动态组件， 所以必须要要提前申明了
type TabType = "component" | "layer" | "page";

const store = useStore<GlobalDataProps>();
// 左侧默认数据
// type LTextType = Partial<TextComponentProps> & {
// tag?: string;
// };
const componentsText = ref<any>(defaultTextTemplates);
const componentsShape = ref<any>(defaultShapeTemplates);

// 画布默认数据
const components = computed(() => store.state.editor.components);
console.log("editor", JSON.stringify(components.value));

//点击前前是null
const currentElement = computed<ComponentData | null>(() => {
  return store.getters.getCurrentElement;
});

const activaPanel = ref<TabType>("component");
const page = computed(() => store.state.editor.page);

const addItem = (component: any) => {
  console.log("editor addItem", component);
  store.commit("addComponent", component);
};

const deleteItem = (id: string) => {
  store.commit("deleteComponent", id);
};

//选中事件
const setActive = (id: string) => {
  store.commit("setActive", id);
};

// 属性编辑发出来的属性变化事件
const handleChange = (e: any) => {
  console.log("editor change", e);
  store.commit("updateComponent", e);
};
const pageChange = (e: any) => {
  console.log("page change", e);
  store.commit("updatePage", e);
};

const titleChange = (newTitle: string) => {
  store.commit("updatePage", { key: "title", value: newTitle, isRoot: true });
};


const changePosition = (data: {id: string;left: number;top: number;width: number;height: number}) => {
  const { id } = data;
  const newPair = mapValues(
    pickBy(data, (v, k) => k !== "id"),
    (value) => {
      return value + "px";
    }
  );
  const keysArr = Object.keys(newPair);
  const valuesArr = Object.values(newPair);
  store.commit("updateComponent", {
    key: keysArr,
    value: valuesArr,
    id,
    isProps: true,
  });
};

// 修改后自动保存
onMounted(()=>{
  if(currentWorkId){
    store.dispatch("fetchWork", {urlParams: {id: currentWorkId}});
  }
})

const publish = async () => {
  // 选中状态取消
  store.commit("setActive", "");
  const el = document.getElementById("canvas-ares") as HTMLElement;
  canvasFix.value = true;
  await nextTick();
  try {
    await publishWork(el);
    showPublishForm.value = true;
  } catch (e) {
    console.error(e);
  } finally {
    canvasFix.value = false;
  }
  // 预览截图的代码 测试使用
  // const image = document.getElementById("test-image") as HTMLImageElement;

  // html2canvas(el, {width: 375, 
  //   useCORS: true,   // 允许背景跨域图片
  //   scale: 1   //解决devicePixelRatio问题
  // }).then((canvas) => {
  //   const dataUrl = canvas.toDataURL("image/png", 1.0);

  //   image.src = dataUrl;
  // });
};

const preview = async () => {
  await saveWork();
  showPreviewForm.value = true;
}


// let dragCurrent = "";
// let offsetX = 0;
// let offsetY = 0;
// let bodyX = 0;
// let bodyY = 0;
// const bodyContainer = ref<HTMLElement | null>();
// const onDragStart = (e: DragEvent,id: string,props: Partial<AllComponentProps>) => {
//   if (!bodyContainer.value) return;
//   dragCurrent = id;
//   const target = e.currentTarget as HTMLElement;
//   console.log(target);
//   const rect = target.getBoundingClientRect();
//   const bodyrec = bodyContainer.value.getBoundingClientRect();
//   bodyX = bodyrec.left;
//   bodyY = bodyrec.top;
//   // 计算鼠标相对于元素左上角的偏移量
//   offsetX = e.clientX - rect.left;
//   offsetY = e.clientY - rect.top;
//   console.log(`[${e.clientX}  ${rect.left}   ${bodyX}]\n
//   [${e.clientY}   ${rect.top}   ${bodyY}]`);
// };

// const onDragOver = (e: DragEvent) => {
//   e.preventDefault();
// };
// const onDrop = (e: DragEvent) => {
//   e.preventDefault();
//   const target = e.currentTarget as HTMLElement;
//   console.log(target);
//   const rect = target.getBoundingClientRect();

//   // 计算元素的新位置，减去偏移量
//   const endX = e.clientX - offsetX - bodyX;
//   const endY = e.clientY - offsetY - bodyY;
//   console.log(`x [${e.clientX}  ${rect.left}   ${bodyX}]\n
//   y [${e.clientY}   ${rect.top}   ${bodyY}]`);

//   store.commit("updateComponent", {
//     key: "position",
//     value: "absolute",
//     id: dragCurrent,
//   });
//   store.commit("updateComponent", {
//     key: "left",
//     value: endX + "px",
//     id: dragCurrent,
//   });
//   store.commit("updateComponent", {
//     key: "top",
//     value: endY + "px",
//     id: dragCurrent,
//   });
// };

</script>

<style scoped lang="css">
.preview-container {
  margin: 0;
  /* min-height: 90vh; */
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.sidebar-container {
  height: 100%;
  width: 100%;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.preview-container .preview-list {
  padding: 0;
  margin: 0;
  min-width: 375px;
  min-height: 200px;
  border: 1px solid #efefef;
  background: #fff;
  overflow-x: hidden;
  overflow-y: auto;
  position: fixed;
  margin-top: 50px;
  max-height: 80vh;
}

.body-container {
  position: relative;
}
 .no-topradius{
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

.page-title{
  display: flex;
  margin-left: 10vw;
}

.page-title img{
  height: 64px;
  object-fit: cover;
  flex: 0 1 30%;
}

.ant-layout-header{
  display: flex;
  justify-content: space-between;
}
.ant-menu {
  flex: 0 2 40%;
}

.preview-list.canvas-fix .edit-wrapper > * {
  box-shadow: none !important;
}

.preview-list.canvas-fix {
  position: absolute;
  max-height: none;
}
</style>
